package pl.freetimetool.dao;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public class HolidaysInPolandDaoImpl implements HolidaysInPolandDao {
	
	@PersistenceContext
	EntityManager entityManager;
	
	private Set <Date> polishHolidaysSet;
	
	@Override
	public boolean isPolishHoliday(String dateToCheck) throws ParseException{
		
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		return isPolishHoliday(formatter.parse(dateToCheck)); 
	}
	
	@Override
	public boolean isPolishHoliday(Date dateToCheck){
		
		if(polishHolidaysSet== null){
			polishHolidaysSet = createPolishHolidaysSet();
		}
		
		return polishHolidaysSet.contains(dateToCheck);
	}
	
	private Set <Date> createPolishHolidaysSet(){
		
		Query query =  entityManager
				.createNativeQuery("SELECT holidayDate FROM holidaysinpoland;");
		List <?> result = query.getResultList();
		
		Set <Date> resultSet  = new HashSet<Date>(result.size());
		for(Object singleResult:result){
			resultSet.add((Date )singleResult);
		}
		
		return resultSet;
	}
	
	

}
